<template>
	<view class="full-page">
		<form>
			<cu-custom bgColor="mybg-green">
				<block slot="content">北海日报订报
				</block>
			</cu-custom>

			<scroll-view scroll-y style="height:calc(100vh - 155px);">
				<form>
					<view class="padding bg-white margin-top flex-row justify-between" style="">
						<view class="myfont-15px text-black">寄报地区</view>
						<view>
							<view class="uni-list">
								<view class="uni-list-cell">
									<view class="uni-list-cell-db">
										<picker @change="bindPickerChange" :value="index" :range="regions"
											v-model="news_info.region" style="padding: 0px;">
											<view class="uni-input myfont-15px">{{regions[index]}} <text
													class="cuIcon-unfold myfont-15px margin-left-xs"></text></view>
										</picker>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view class="cu-form-group margin-top">
						<view class="uni-title uni-common-pl myfont-15px">地址:</view>
						<input name="input" class="" style="text-align: right;font-size: 15px;padding: 0;"
							placeholder=" XX省XX市" v-model="news_info.province_city" :disabled="isDisabled"></input>
					</view>
					<view class="cu-form-group">
						<view class="title">详细地址:</view>
						<input name="input" style="text-align: right;" placeholder="XX区XX街道XX小区XX楼座"
							v-model="news_info.address"></input>
					</view>
					<view class="cu-form-group">
						<view class="title">邮编:</view>
						<input name="input" type="number" style="text-align: right;"
							v-model="news_info.postcode"></input>
					</view>
					<view>
						<view class="cu-form-group myborder">
							<view class="title">收货人:</view>
							<input name="input" style="text-align: right;" v-model="news_info.receiver"></input>
						</view>
					</view>

					<view class="cu-form-group myborder">
						<view class="title">手机号码:</view>
						<input name="input" type="number" maxlength="13" style="text-align: right;"
							v-model="news_info.phone"></input>
					</view>
					<view class="cu-form-group margin-top">
						<view class="title">订单备注:</view>
						<input name="input" style="text-align: right;" v-model="news_info.remark"></input>
					</view>

					<view class="bg-white flex-row justify-between padding myborder">
						<view class="text-black" style="width: 64px;font-size: 16px;">选择期限</view>
						<view class="flex-row justify-center">
							<picker mode="date" fields="month" style="text-align: right;" :start="start_date"
								:end="end_date" :value="news_info.start_date" @change="bindDateChange"
								v-model="news_info.start_date">
								<view class="uni-input">{{ news_info.start_date }}<text
										class="cuIcon-unfold myfont-15px margin-left-xs"></text></view>
							</picker>
							<view class="padding-lr"></view>
							<view class="title" style="text-align: center;">------</view>
							<view class="padding-lr"></view>
							<picker mode="date" fields="month" style="text-align: right;" :start="news_info.start_date"
								:end="end_date" :value="news_info.end_date" @change="bindDateChange2"
								v-model="news_info.end_date">
								<view class="uni-input">{{ news_info.end_date }}<text
										class="cuIcon-unfold myfont-15px margin-left-xs"></text></view>
							</picker>
							<view class="cu-capsule radius">
								<!-- <view class='cu-tag bg-blue '>
							      +86
							    </view> -->
								<!-- <view class="cu-tag line-blue">
							      中国大陆
							    </view> -->
							</view>
						</view>

					</view>

					<view class="cu-form-group margin-top">
						<view class="title">报纸数量</view>
						<input class="uni-input" controls-position="right" style="text-align: right;" type="number"
							placeholder="输入数量" v-model="news_info.amount" />份
					</view>
					<view class="cu-form-group" v-if="!next_year">
						<view class="title" style="padding: 0;">收费标准</view>
						<input name="input" v-model="news_info.charge_standard"
							v-if="!next_year">报纸一份每月{{price}}元，外地（邮寄）
						每份报纸每月加收15元邮费,最多预定{{month}}个月。</input>
					</view>
					<view class="cu-form-group" v-if="next_year">
						<view class="title" style="padding: 0;">收费标准</view>
						<input name="input" v-model="news_info.charge_standard"
							v-if="next_year">报纸一份今年部分每月{{price}}元，明年部分每月{{next_price}}元，外地（邮寄）
						每份报纸每月加收15元邮费,最多预定{{month}}个月。</input>
					</view>
					<view class="padding bg-white margin-top flex-row justify-between" style="">
						<view class=" myfont-15px text-black" style="">购买主体</view>
						<view>
							<view class="uni-list">
								<view class="uni-list-cell">
									<view class="uni-list-cell-db">
										<picker @change="bindPickerChange2" :value="index2" :range="buyers"
											v-model="news_info.buyer">
											<view class="uni-input">{{buyers[index2]}}<text
													class="cuIcon-unfold myfont-15px margin-left-xs"></text></view>
										</picker>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view class="cu-form-group">
						<view class="title">验证码</view>
						<input name="input" v-model="news_info.security_code"></input>
						<view class="code-img-wrapper" @click="updateImageCode">
							<canvas style="width:220rpx;height:86rpx;" canvas-id="canvas"></canvas>
						</view>
					</view>
					<view class="cu-form-group">
						<view class="" style="width: 75%;">
							<view class="margin-left" v-if="!next_year">
								{{news_info.months}}个月 , {{news_info.amount}}份
								总额
								<uni-text data-v-4d87e8e4 class="text-price text-red">
									{{cal_total_amount()}}
								</uni-text>
							</view>
							<view class="margin-left" v-if="next_year">
								今年部分{{news_info.months}}个月 , 明年部分{{news_info.months_next}}个月 , {{news_info.amount}}份
								总额
								<uni-text data-v-4d87e8e4 class="text-price text-red">
									{{cal_total_amount()}}
								</uni-text>
							</view>
						</view>
						<button class="margin-right"
							style="width: 20%;height: 40px;font-size: 13px;padding: 3px;margin-left: 4%;" type="primary"
							@click="submit">提交订单</button>
					</view>
					<view class="cu-form-group justify-center flex-column myfont-18px">
						<text class="">主办单位：北海市融媒体中心</text>
						<text>咨询电话：0779-2030018</text>
					</view>
					<!-- <view cllass="code-img-wrapper" @click="updateImageCode">
						<canvas style="width: 220rpx;height: 86rpx;" canvas-id="canvas"></canvas>
					</view> -->
				</form>
			</scroll-view>
		</form>


		<view class="box safe-area box-shadow">

			<view class="cu-bar tabbar bg-white">
				<view class="action mycolor-green">
					<view class="cuIcon-homefill"></view>
					<view>订报</view>
				</view>
				<view class="action text-gray" @click="to_page('../orders/order_form')">
					<view class="cuIcon-read grayscale"></view>
					<view>小记者订报</view>
				</view>
				<view class="action text-gray" @click="to_page('../orders/order_list')">
					<view class="cuIcon-pay grayscale"></view>
					<view>我的订单</view>
				</view>
			</view>
		</view>

		<view class="cu-modal" :class="modalName=='userModal'?'show':''" @tap="closeModal()">
			<view class="cu-dialog" style="width: 300px;">
				<view class="loginView">
					<view class="loginTitle" style="">授权获取个人信息</view>
					<image src="../../static/wxProgram.png"></image>
					<view>申请获取您微信的头像、昵称！</view>
					<button class='cu-btn bg-green shadow' :disabled="loginDisable" @click="wxGetUserInfo">授权登录</button>
				</view>
			</view>
		</view>

		<view class="cu-modal" :class="modalName=='phoneModal'?'show':''">
			<view class="cu-dialog" style="width: 300px;">
				<view class="loginView">
					<view class="loginTitle" style="">授权获取手机号</view>
					<image src="../../static/wxProgram.png"></image>
					<view>授权获取手机号！</view>
					<button class='cu-btn phone bg-green' open-type="getPhoneNumber"
						@getphonenumber="getPhoneNumber">授权手机号</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import dateFormatUtils from '../../utils/utils.js'
	import common from '../../utils/common.js'
	import config from '../../utils/config.js'
	import {
		Mcaptcha
	} from '@/utils/mcaptcha'
	export default {
		components: {},
		data() {
			return {
				swiperList: [{
						id: 0,
						type: 'image',
						url: '../../static/image/bg-ucenter.png'
					},
					{
						id: 1,
						type: 'image',
						url: '../../static/image/bg-ucenter.png'
					},
					{
						id: 2,
						type: 'image',
						url: '../../static/image/bg-ucenter.png'
					},
				],
				modalName: '',
				firstLogin: true,
				loginDisable: false,
				phone: uni.getStorageSync('phone') || '',
				userInfo: uni.getStorageSync('userInfo') || null,
				isLogin: uni.getStorageSync('isLogin') || false,
				news_info: {
					region: '',
					province_city: '广西北海市',
					address: '',
					postcode: '',
					receiver: '',
					phone: '',
					remark: '',
					amount: '1',
					buyer: '',
					security_code: '',
					// start_date: this.getCurrentMonth(),
					start_date: this.getNextMonth(1),
					end_date: this.getNextMonth(1),
					months: 1,
					months_next: 0,
					subscription_type: '',
					school: '',
					classes: '',
					student_name: '',
				},
				check_list: config.order_check_list,
				start_date: this.getNextMonth(1),
				end_date: this.getCurrentMonth(0),
				regions: ['北海市辖区', '其他地区'],
				index: 0,
				buyers: ['个人', '单位'],
				subscription: ['普通订报', '小记者订报'],
				index2: 0,
				index3: 0,
				modalName: null,
				order_info: null,
				price: 40,
				next_price: 40,
				month: 6,
				price1: 40,
				month1: 3,
				isDisabled: true,
				next_year: false,
			};
		},

		methods: {
			getNextMonth(offset) {
				const currentDate = new Date();
				currentDate.setDate(1); // 先将日期设置为月份的第一天
				currentDate.setMonth(currentDate.getMonth() + offset); // 增加月份

				const year = currentDate.getFullYear();
				const month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
				console.log(month)
				return `${year}-${month}`;
			},
			getCurrentMonth() {
				const date = new Date()
				let year = date.getFullYear()
				let month = date.getMonth() + 1
				month = month > 9 ? month : '0' + month
				console.log(month)
				return `${year}-${month}`
			},
			closeModal() {
				this.modalName = ''
			},
			openDialogs: function() {
				// this.$refs.popup.open()
				this.modalName = 'userModal'
			},
			to_page(page) {
				// console.log(this.isLogin)
				// console.log(page)
				if (!this.isLogin && page == '../orders/order_list') {
					this.checkToken()
					return
				}
				// else {
				// 	if (this.price1 == 0
				// 		// || this.month1 == 0
				// 	) {
				// 		uni.showToast({
				// 			title: '小记者订报暂未开放',
				// 			icon: 'none',
				// 			duration: 2000,
				// 			mask: true
				// 		});
				// 		return
				// 	} else {
				// 		uni.navigateTo({
				// 			url: page
				// 		})
				// 	}
				// 	// uni.reLaunch({
				// 	// 	url: page
				// 	// })
				// }
				uni.navigateTo({
					url: page
				})
			},
			getPhoneNumber(e) {
				var _this = this;
				uni.showLoading({
					title: '正在获取手机号'
				})
				uni.checkSession({
					success() {
						if (e.detail.errMsg != "getPhoneNumber:fail user deny") {
							//调用后端服务获取解密后的手机号
							_this.$http.post('app/app_user/upload_phone', {
								encryptedData: e.detail.encryptedData,
								iv: e.detail.iv
							}, {}, (res) => {
								uni.hideLoading();
								if (res.data.code == 20000) {
									uni.showToast({
										title: '获取成功！'
									})
									//获取业主信息
									_this.phone = res.data.phone;
									uni.setStorageSync('phone', _this.phone);
									_this.modalName = null;
									_this.getInfo()
								} else {
									uni.showToast({
										title: '登录信息过期，请重新登录！',
										success: function(resp) {
											_this.modalName = null;
											_this.isLogin = false;
											uni.removeStorageSync('phone')
											uni.removeStorageSync('isLogin')
										}
									})
								}
							});

						} else {
							console.log("用户拒绝授权")
							_this.back()
						}
					},
					fail() {
						_this.login();
					}
				})
			},
			// 获取个人信息
			getInfo() {
				var _this = this;
				var para = {}
				_this.$http.get('app/app_user', {
					data: para
				}, (res) => {
					if (res.data.code == 20000) {
						let info = res.data.info
						uni.setStorageSync('userInfo', info);
						_this.userInfo = info
					} else if (res.data.code == 40001 || res.statusCode == 401) {
						_this.removeToken()
						// _this.openDialogs()
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'fail'
						})
					}
				});
			},
			wxGetUserInfo() {
				var _this = this;
				uni.showModal({
					title: '温馨提示',
					content: '亲，授权微信登录后才能正常使用小程序功能',
					success(res) {
						//如果用户点击了确定按钮
						if (res.confirm) {
							uni.showLoading({
								title: '正在获取授权...'
							})
							uni.getUserProfile({
								desc: '获取你的昵称、头像、地区及性别',
								lang: 'zh_CN',
								success: res => {
									_this.userInfo = res.userInfo;
									_this.login();
									uni.setStorageSync('userInfo', _this.userInfo);
								},
								fail: res => {
									//拒绝授权
									wx.showToast({
										title: '您拒绝了请求,不能正常使用小程序',
										icon: 'error',
										duration: 2000
									});
									return;
								}
							});
						} else if (res.cancel) {
							//如果用户点击了取消按钮
							uni.showToast({
								title: '您拒绝了请求,不能正常使用小程序',
								icon: 'error',
								duration: 2000
							});
							return;
						}
					}
				})

			},
			login() {
				let _this = this;
				// 1.wx获取登录用户code
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						let code = loginRes.code;
						//2.将用户登录code传递到后台置换用户SessionKey、OpenId等信息
						_this.getUserToken(code);
					},
				});
			},
			getUserToken(code) {
				let _this = this;
				console.log('开始向服务器获取登录信息！');
				uni.showLoading({
					title: '登录中!'
				})
				_this.loginDisable = true
				_this.$http.get('app/app_user/login', {
					data: {
						code: code,
					}
				}, (res) => {
					uni.hideLoading()
					_this.loginDisable = false
					if (res.data.code == 20000) {
						//说明是没获取到授权 , 需要获取用户信息上次
						if (res.data.nick_name) {
							_this.firstLogin = false;
							uni.setStorageSync('firstLogin', false);
						}
						_this.isLogin = true;
						uni.setStorageSync('userId', res.data.user_id);
						uni.setStorageSync('token', res.data.token);
						uni.setStorageSync('isLogin', true)
						_this.uploadUserInfo();
						_this.$refs.popup.close() //隐藏弹窗
					} else {
						_this.removeToken()
						uni.showToast({
							title: res.data.msg,
							icon: 'fail'
						})
					}
				});
			},
			//将userInfo传给后台
			uploadUserInfo() {
				let _this = this;
				_this.$http.post('app/app_user/upload_info', {
					user_info: _this.userInfo,
				}, (res) => {
					if (res.data.code == 20000) {
						//说明是没获取到授权 , 需要获取用户信息上次
						_this.closeModal()
						console.log("上传用户信息成功!");
						_this.get_dict()
					} else {
						console.log("上传用户信息失败!");
						uni.showToast({
							title: '出错了，请重新授权！',
							icon: 'none',
							complete() {
								setTimeout(() => {
									_this.openDialogs()
								}, 1 * 1000)
							}
						})
					}
				});
			},
			removeToken() {
				this.userInfo = null
				this.isLogin = false
				uni.removeStorageSync('userInfo')
				uni.removeStorageSync('token')
				uni.removeStorageSync('isLogin')
			},
			checkToken() {
				let _this = this;
				if (!_this.isLogin) {
					_this.openDialogs()
					return
				} else {
					_this.getInfo()
				}
				uni.checkSession({
					fail() {
						_this.openDialogs()
						return
					}
				})
			},
			get_orders: function() {
				let _this = this;
				let para = Object.assign({}, _this.listQuery)
				_this.$http.get('/app/order/', {
					data: para
				}, (res) => {
					if (res.data.code == 20000) {
						if (res.data.items.length > 0) {
							let items = res.data.items
							items.forEach((ele, index) => {
								ele.months = _this.monthNumber(ele.start_date, ele.end_date)
								ele.order_date = ele.start_date.slice(0, 7) + '-' + ele.end_date.slice(
									0, 7)
								_this.order_list.push(ele)
							})
							console.log(_this.order_list)
						} else {
							_this.end = true
						}
						// console.log(_this.gym_list)
					} else {}
				});
			},
			addCompleted() {
				var _this = this;
				uni.showLoading({
					title: 'Loading!'
				})
				let para = Object.assign({}, _this.news_info)
				para.start_date += '-01'
				para.end_date += '-01'
				para.region = _this.regions[_this.index]
				para.buyer = _this.buyers[_this.index2]
				para.subscription_type = _this.subscription[_this.index3]
				para.total_fee = _this.cal_total_amount()

				para.amount = _this.news_info.amount
				para.months = _this.news_info.months
				if (!_this.next_year) {
					para.body = `订购报纸${_this.news_info.amount}份${_this.news_info.months}个月，共${para.total_fee}元`
				} else {
					para.body =
						`订购报纸${_this.news_info.amount}份今年部分${_this.news_info.months}个月,明年部分${_this.news_info.months_next}个月，共${para.total_fee}元`

				}
				_this.$http.post("/app/order", para, (res) => {
					uni.hideLoading()
					if (res.data.code == 20000) {
						_this.order_info = res.data.order
						uni.showModal({
							title: '提示',
							showCancel: false,
							content: '下单成功，即将打开支付界面！',
							complete: function(re) {
								if (re.confirm) {
									_this.create_wx_order()
								}
							}
						})
					} else {
						uni.showModal({
							title: '提示',
							showCancel: false,
							content: res.data.message,
							complete: function(re) {
								if (re.confirm) {}
							}
						})
					}
				})
			},
			// cal_total_amount() {
			// 	return this.news_info.amount * [this.news_info.months + 1] * (parseInt(this.price) + (this.regions[this
			// 			.index] === '其他地区' ?
			// 		15 : 0))
			// },
			cal_total_amount() {
				const currentPrice = parseInt(this.price);
				const nextPrice = parseInt(this.next_price);
				const regionFee = this.regions[this.index] === '其他地区' ? 15 : 0;
				if (!this.next_year) {
					return this.news_info.amount * (this.news_info.months) * (currentPrice + regionFee);
				} else {
					return (this.news_info.amount * (this.news_info.months) * (currentPrice + regionFee) + this.news_info
						.amount * (this.news_info.months_next) * (nextPrice + regionFee));
				}
			},
			getCurrentDate: function(n) {
				var dd = new Date();
				if (n) {
					dd.setDate(dd.getDate() - n);
				}
				var year = dd.getFullYear();
				var month =
					dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1;
				var day = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
				return year + "-" + month + "-" + day;
			},
			create_wx_order: function() {
				let _this = this;
				_this.$http.post('app/order/create_wx_order', {
					// 'pay_amount': _this.form.amount * 100,
					// 'pay_type': pay_type.online,
					// 'purpose': pay_purpose.temp_fee,
					// 'body': _this.plateNo + '停车费',
					'order_id': _this.order_info.id,
					// 'pay_amount': payAmount * 100,
					// 'pay_amount': 1,

				}, (res) => {
					// var dat = JSON.parse(res.data)
					let dat = res.data
					// console.log(dat)
					if (dat.code == 20000) {
						var data = dat.data
						uni.requestPayment({
							provider: 'wxpay',
							timeStamp: data.timeStamp,
							nonceStr: data.nonceStr,
							package: data.package,
							signType: data.signType,
							paySign: data.paySign,
							success: function(res) {
								_this.order_info = ''
								uni.showToast({
									title: '支付成功！',
									duration: 1500,
									success() {}
								})
								setTimeout(() => {
									uni.reLaunch({
										url: '/pages/orders/order_list'
									})
								}, 1750)
							},
							fail: function(err) {
								console.log('fail:' + JSON.stringify(err));
							}
						});
					} else {
						console.log('error:' + res);
					}
				});
			},
			onReady() {
				this.mcaptcha = new Mcaptcha({
					el: 'canvas',
					width: 80,
					height: 35,
					createCodeImg: ""
				});
			},
			// 刷新验证码
			updateImageCode() {
				this.mcaptcha.refresh()
			},
			// 提交前校验图形验证码
			submit() {
				let content = ''
				let _this = this
				if (!_this.isLogin) {
					_this.checkToken()
					return
				}
				let check_list = JSON.parse(JSON.stringify(_this.check_list))

				check_list.some(ele => {
					let val = _this.news_info[ele.value]
					if (ele.reg && !config[ele.reg].test(val)) {
						content = ele.tips
						return true
					} else if (!val) {
						content = ele.tips
						return true
					}
				})
				let validate = this.mcaptcha.validate(this.news_info.security_code)
				if (!validate) {
					content = '图形验证码错误'
				}
				if (content) {
					uni.showToast({
						title: content,
						icon: 'none'
					})
				} else {
					this.addCompleted()
				}
			},
			bindPickerChange: function(e) {
				this.index = e.detail.value;
				if (this.index == 0) {
					this.news_info.province_city = '广西北海市'
					this.isDisabled = true
				} else {
					this.news_info.province_city = ''
					this.isDisabled = false
				}
			},
			bindPickerChange2: function(e) {
				this.index2 = e.detail.value;
			},
			formatDate(date) {
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				return `${year}-${month}`;
			},
			bindDateChange(e) {
				const newStartDate = e.target.value;
				const newEndDate = this.news_info.end_date;

				if (this.isDateValid(newStartDate, newEndDate)) {
					this.news_info.start_date = newStartDate;
					this.calculateMonths();
				} else {
					uni.showToast({
						title: '开始日期不能晚于结束日期，请先选择结束日期',
						icon: 'none',
						duration: 2000,
						mask: true,
					});
				}
			},
			bindDateChange2(e) {
				const newEndDate = e.target.value;
				const newStartDate = this.news_info.start_date;

				if (this.isDateValid(newStartDate, newEndDate)) {
					this.news_info.end_date = newEndDate;
					this.calculateMonths();
				} else {
					uni.showToast({
						title: '请选择正确的日期范围和顺序',
						icon: 'none',
						duration: 2000,
						mask: true,
					});
				}
			},
			calculateMonths() {
				const startDate = new Date(this.news_info.start_date);
				const endDate = new Date(this.news_info.end_date);
				const yearDiff = endDate.getFullYear() - startDate.getFullYear();
				const monthDiff = endDate.getMonth() - startDate.getMonth();
				const dayDiff = endDate.getDate() - startDate.getDate();
				let diffMonths = yearDiff * 12 + monthDiff;
				// 根据新规则进行调整
				if (startDate.getMonth() === new Date().getMonth()) {
					diffMonths = monthDiff;
				} else {
					diffMonths = diffMonths + 1;
				}
				if (dayDiff > 0) {
					diffMonths += 1;
				}
				if (!this.next_year) {
					this.news_info.months = Math.max(diffMonths, 1);
				} else {
					const currentMonth = new Date().getMonth() + 1;
					let total_months_diff = Math.max(diffMonths, 1)
					let current_months_diff = 12 - currentMonth
					let next_months_diff = total_months_diff - current_months_diff
					// next_months_diff大于0则表示有选到明年的月份
					this.news_info.months = next_months_diff > 0 ? current_months_diff : total_months_diff;
					this.news_info.months_next = next_months_diff > 0 ? next_months_diff : 0
				}
				console.log(this.news_info.months, this.news_info.months_next)
			},
			isDateInRange(date, minDate, maxDate) {
				const selectedDate = new Date(date);
				return selectedDate >= minDate && selectedDate <= maxDate;
			},
			isDateValid(startDate, endDate) {
				const start = new Date(startDate);
				const end = new Date(endDate);
				// 判断开始日期是否在结束日期之前
				if (start > end) {
					return false;
				}
				// 判断开始日期是否是本月，如果是，结束日期必须大于开始日期
				const today = new Date();
				if (start.getFullYear() === today.getFullYear() && start.getMonth() === today.getMonth()) {
					return end > start;
				}
				return true;
			},
			monthNumber: function(date1_str, date2_str) {
				const date1 = new Date(date1_str);
				const date2 = new Date(date2_str);
				const month_between = (date2.getFullYear() - date1.getFullYear()) * 12 + date2.getMonth() - date1
					.getMonth()
				return Math.abs(month_between);
			},
			PickerChange(e) {
				this.index = e.detail.value
			},
			DateChange(e) {
				this.date = e.detail.value
			},
			get_dict() {
				let _this = this;
				let para = Object.assign({}, _this.para_lsit);
				_this.$http.get('/app/dict', {}, (res) => {
					if (res.data.code == 20000) {
						const dictItems = res.data.items;
						for (const item of dictItems) {
							// if (item.name === "可订月份") {
							//     _this.month = item.content;
							//     console.log(_this.end_date, _this.month)
							// } 
							if (item.name === "每月金额") {
								_this.price = item.content;
							}
							if (item.name === "次年每月金额") {
								_this.next_price = item.content;
							}
						}
						const currentMonth = new Date().getMonth() + 1;
						// const currentMonth = new Date(2024, 0, 1).getMonth() + 1;
						console.log(currentMonth)
						if (currentMonth >= 1 && currentMonth <= 9) {
							_this.month = 12 - currentMonth;
						} else {
							_this.month = 12 - currentMonth + 12;
							_this.next_year = true
						}
						// 获取下个月日期
						const currentDate = new Date();
						// const currentDate = new Date(2024, 0, 1);
						currentDate.setDate(1); // 将日期设置为 1 号，以避免月份溢出
						currentDate.setMonth(currentDate.getMonth() + parseInt(_this.month));
						const year = currentDate.getFullYear();
						const month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
						_this.end_date = `${year}-${month}`;
						console.log(_this.end_date, _this.month);
						if (_this.next_year) {
							_this.calculateMonths()
						}
					} else {}
				});
				console.log(_this.next_year)
			},
			getUserCroodsToken() {
				croods.customPlugin({
					action: "UserPlugin.login",
					params: {},
					success: (res) => {
						if (res.token) {
							uni.setStorageSync('croods_token', res.token);
						}
					}
				});
			},
		},
		onShow() { //默认加载
			// console.log(this.$http.baseUrl)
		},
		onShareAppMessage(el) {
			return {
				title: '北海日报社在线订报',
				path: '/pages/index/index'
			}
		},
		onLoad(option) {
			let _this = this;
			// let firstLogin = uni.getStorageSync('firstLogin')
			// if (_this.isLogin && !firstLogin) {
			// 	_this.checkToken()
			// }
			// if (!this.isLogin) {
			// 	this.checkToken()
			// }
			_this.get_dict()
			// _this.getUserCroodsToken()
		}
	}
</script>

<style lang="scss">
	.box {
		margin: 0 0 0 0;
		position: fixed;
		bottom: 0px;
		width: 100vw;

		.safe-area {
			padding-bottom: constant(safe-area-inset-bottom);
			padding-bottom: env(safe-area-inset-bottom);
		}
	}


	.box view.cu-bar {
		padding-top: 20upx;
	}

	.flex-row {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: row;
	}


	.loginView {
		text-align: center;
		width: 300px;
		border-radius: 8px;
		background-color: white;
	}

	.loginView image {
		margin: 8px;
		width: 50px;
		height: 50px;
	}


	.loginView button {
		width: 250px;
		height: 45px;
		margin: 10px;
		border-radius: 20px;
	}

	.loginView .loginTitle {
		height: 50px;
		line-height: 50px;
		border-bottom: 1px solid lightgrey;
	}

	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}

	.myborder {
		border-top: 1rpx solid #eee;
	}
</style>